import {
  FC,
  ReactElement,
  useMemo,
  useCallback,
  useEffect,
  useState,
} from "react";
import styled from "styled-components";
import { getPokers, PokerProps } from "../../../api/pokerAPI";
import EditPoker from "./EditPoker";
import PokerList from "./PokerList";

interface IProps {}

const PokerManage: FC<IProps> = (): ReactElement => {
  const [pokerList, setPokerList] = useState<any>([]);
  const [update, setUpdate] = useState<any>(false);
  const [updateData, setUpdateData] = useState<any>(undefined);
  const pokerLength = useMemo(() => pokerList.length, [pokerList]);

  useEffect(() => {
    getPokers()
      .then(res => {
        console.log("/getPokers", res.data);
        setPokerList(res.data);
      })
      .catch(err => {
        console.log("pokers err", err);
      });
  }, []);

  const onCreateNewPoker = useCallback(poker => {
    setPokerList((prev: any) => {
      const list = [...prev];
      const index = list.findIndex(
        ({ level }: PokerProps) => level < poker.level
      );
      list.splice(index === -1 ? list.length : index, 0, poker);
      return list;
    });
  }, []);
  //数据服务端更新后本地更新
  const handleUpdatePoker = useCallback((pokerFields: Partial<PokerProps>) => {
    setPokerList((prev: any) => {
      const list = [...prev];
      const index = list.findIndex(
        ({ _id }: PokerProps) => _id === pokerFields._id
      );
      const newPoker = { ...list[index], ...pokerFields };
      if (
        pokerFields.level !== undefined &&
        list[index].level !== pokerFields.level
      ) {
        //位置发生变化了
        list.splice(index, 1);
        const newIndex = list.findIndex(
          ({ level }: PokerProps) => level < newPoker.level
        );
        list.splice(newIndex, 0, newPoker);
      } else {
        list[index] = newPoker;
      }
      return list;
    });
  }, []);

  const onDeletePoker = useCallback(index => {
    setPokerList((prev: any) =>
      prev.filter((poker: any) => poker._id !== index)
    );
  }, []);

  const onUpdatePoker = useCallback(
    (poker: PokerProps) => () => {
      setUpdateData(poker);
      setUpdate(true);
    },
    []
  );
  const onCancelUpdatePoker = useCallback(() => {
    setUpdate(false);
  }, []);

  return (
    <Container>
      <EditPoker
        update={update}
        updateData={updateData}
        onCreateNewPoker={onCreateNewPoker}
        onCancelUpdatePoker={onCancelUpdatePoker}
        handleUpdatePoker={handleUpdatePoker}
        pokerLength={pokerLength}
      />
      <PokerList
        pokerList={pokerList}
        onDeletePoker={onDeletePoker}
        onUpdatePoker={onUpdatePoker}
      />
    </Container>
  );
};

export default PokerManage;

const Container = styled.div`
  width: 100%;
  height: 100%;
  background-color: #fff;
  padding: 20px;
  display: flex;
`;
